import React, { useEffect, useRef, useState, useCallback } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { Box, CircularProgress, Alert, Typography } from '@mui/material';
import { useWebSocket } from './WebSocketContext';

// 卫星状态颜色映射
const STATUS_COLORS = {
  online: '#4caf50',  // 绿色
  offline: '#f44336', // 红色
  alert: '#9e9e9e'    // 灰色
};

// 轨道类型高度映射（比例因子）
const ORBIT_ALTITUDE_FACTORS = {
  leo: 0.15,  // 低轨道
  meo: 0.25,  // 中轨道
  geo: 0.35,   // 地球同步轨道
  sgo: 0.40   // 静轨威慑层
};

// 轨道颜色映射
const ORBIT_COLORS = {
  leo: '#64b5f6', // 浅蓝色
  meo: '#ba68c8', // 紫色
  geo: '#ffd54f',  // 黄色
  sgo: '#ffd54f'  // 黄色 (静轨威慑层)
};

// 轨道面配置
const ORBIT_PLANES = {
  // 低轨突击层轨道面 (LEO-01~12，Walker Delta类型，升交点赤经30°递增)
  "LEO-01": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 0
  },
  "LEO-02": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 30
  },
  "LEO-03": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 60
  },
  "LEO-04": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 90
  },
  "LEO-05": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 120
  },
  "LEO-06": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 150
  },
  "LEO-07": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 180
  },
  "LEO-08": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 210
  },
  "LEO-09": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 240
  },
  "LEO-10": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 270
  },
  "LEO-11": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 300
  },
  "LEO-12": { 
    type: "leo", 
    altitude: 0.35, 
    inclination: 35, 
    color: '#64b5f6',
    raan: 330
  },
  // 太阳同步轨道补充
  "LEO-SSO": { 
    type: "leo", 
    altitude: 0.50, 
    inclination: 98, 
    color: '#4fc3f7', 
    raan: 0
  },
  
  // 中轨警戒层轨道面 - 极轨道面 (6个，0°-180°间隔)
  "MEO-POLAR-01": { 
    type: "meo", //轨道类型
    altitude: 0.85, //轨道高度
    inclination: 90, //轨道倾角
    color: '#9c27b0', //轨道颜色
    raan: 0 //升交点赤经
  },
  "MEO-POLAR-02": { 
    type: "meo", 
    altitude: 0.85, 
    inclination: 90, 
    color: '#9c27b0',
    raan: 30
  },
  "MEO-POLAR-03": { 
    type: "meo", 
    altitude: 0.85, 
    inclination: 90, 
    color: '#9c27b0',
    raan: 60
  },
  "MEO-POLAR-04": { 
    type: "meo", 
    altitude: 0.85, 
    inclination: 90, 
    color: '#9c27b0',
    raan: 90
  },
  "MEO-POLAR-05": { 
    type: "meo", 
    altitude: 0.85, 
    inclination: 90, 
    color: '#9c27b0',
    raan: 120
  },
  "MEO-POLAR-06": { 
    type: "meo", 
    altitude: 0.85, 
    inclination: 90, 
    color: '#9c27b0',
    raan: 150
  },
  
  // 中轨警戒层轨道面 - 60°轨道面 (6个，60°等差)
  "MEO-01": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 0
  },
  "MEO-02": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 60
  },
  "MEO-03": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 120
  },
  "MEO-04": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 180
  },
  "MEO-05": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 240
  },
  "MEO-06": { 
    type: "meo", 
    altitude: 0.95, 
    inclination: 60, 
    color: '#ba68c8',
    raan: 300
  },
  
  // 地球同步轨道
  "GEO": { 
    type: "geo", 
    altitude: 1.8, 
    inclination: 0, 
    color: '#ffd54f',
    raan: 0
  },
  // 静轨威慑层 - 西太组
  "SGO-WEST": { 
    type: "sgo", 
    altitude: 1.9, 
    inclination: 0, 
    color: '#ffd54f', 
    raan: 120 
  },
  // 静轨威慑层 - 印度洋组
  "SGO-INDIAN": { 
    type: "sgo", 
    altitude: 1.95, 
    inclination: 0, 
    color: '#ffd54f', 
    raan: 70 
  }
};

/**
 * 根据轨道面的参数(高度,倾角,升交点赤经)生成轨道点集,用于绘制轨道线
 */
const generateOrbitPoints = (orbitPlane) => {
  const { altitude, inclination, raan } = orbitPlane;
  const points = [];
  
  // 生成轨道点
  const segments = 120; // 增加轨道分段数，使轨道更平滑
  for (let i = 0; i < segments; i++) {
    const angle = (i / segments) * Math.PI * 2;
    
    // 计算基本位置
    const r = 1 + altitude;
    const x = r * Math.cos(angle);
    const y = r * Math.sin(angle) * Math.cos(inclination * Math.PI / 180);
    const z = r * Math.sin(angle) * Math.sin(inclination * Math.PI / 180);
    
    // 应用升交点赤经旋转
    const raanRad = raan * Math.PI / 180;
    const xRot = x * Math.cos(raanRad) - z * Math.sin(raanRad);
    const zRot = x * Math.sin(raanRad) + z * Math.cos(raanRad);
    
    points.push([xRot, y, zRot]);
  }
  // 闭合轨道
  points.push(points[0]);
  return points;
};

/**
 * 将三维直角坐标(x,y,z)转换为地理坐标(纬度,经度)
 */
const cartesianToLatLng = (x, y, z) => {
  const r = Math.sqrt(x*x + y*y + z*z);
  const lat = Math.asin(y / r) * 180 / Math.PI;
  const lng = Math.atan2(z, x) * 180 / Math.PI;
  return { lat, lng };
};
/**
 * 根据轨道点集,时间戳,卫星ID,轨道速度,初始相位,卫星索引,总卫星数计算卫星在轨道面上的位置
 */
const calculateSatellitePosition = (orbitPoints, timestamp, satelliteId, orbitSpeed = 1, initialPhase = 0, satelliteIndex = 0, totalSatellites = 1) => {
  if (!orbitPoints || orbitPoints.length <= 1) {
    return { lat: 0, lng: 0, alt: 0 };
  }
  
  // 轨道点数量减1是因为最后一个点是闭合轨道重复的第一个点
  const effectivePoints = orbitPoints.length - 1;
  
  // 均匀分布卫星的初始相位
  // 如果该轨道面上有多个卫星，则均匀分布它们的初始相位
  let satellitePhase = 0;
  if (totalSatellites > 1) {
    satellitePhase = (satelliteIndex / totalSatellites);
  }
  
  // 将初始相位和卫星在轨道面上的均匀分布结合
  const combinedPhase = (initialPhase + satellitePhase) % 1;
  
  // 计算当前时间偏移，确保同一轨道面上的卫星速度一致
  // 使用轨道速度因子调整不同轨道面的速度
  const timeOffset = (timestamp / (30000 / orbitSpeed)) % 1;
  
  // 计算当前位置索引，考虑相位
  const currentIndex = (combinedPhase + timeOffset) % 1 * effectivePoints;
  
  // 计算当前索引的小数部分和整数部分
  const indexFloor = Math.floor(currentIndex) % effectivePoints;
  const indexFraction = currentIndex - Math.floor(currentIndex);
  const nextIndex = (indexFloor + 1) % effectivePoints;
  
  // 获取三维点
  const point1 = orbitPoints[indexFloor];
  const point2 = orbitPoints[nextIndex];
  
  // 线性插值计算精确三维位置
  const x = point1[0] + (point2[0] - point1[0]) * indexFraction;
  const y = point1[1] + (point2[1] - point1[1]) * indexFraction;
  const z = point1[2] + (point2[2] - point1[2]) * indexFraction;
  
  // 计算卫星高度
  const r = Math.sqrt(x*x + y*y + z*z);
  const alt = r - 1;
  
  // 转换为经纬度
  const { lat, lng } = cartesianToLatLng(x, y, z);
  
  return { lat, lng, alt };
};

/**
 * 将卫星按照轨道类型分配到不同的轨道面上
 */
const assignSatellitesToOrbitPlanes = (satellites) => {
  if (!Array.isArray(satellites) || satellites.length === 0) {
    return {};
  }
  const satellitesByOrbit = {};
  // 初始化轨道面列表
  Object.keys(ORBIT_PLANES).forEach(planeId => {
    satellitesByOrbit[planeId] = [];
  });
  // 按轨道类型分配卫星
  const leoSatellites = satellites.filter(sat => sat && sat.orbitType === 'leo');
  const meoSatellites = satellites.filter(sat => sat && sat.orbitType === 'meo');
  const geoSatellites = satellites.filter(sat => sat && sat.orbitType === 'geo');
  const sgoSatellites = satellites.filter(sat => sat && sat.orbitType === 'sgo');
  // 获取所有LEO轨道面
  const leoPlanes = Object.keys(ORBIT_PLANES).filter(id => id.startsWith('LEO-') && id !== 'LEO-SSO');
  const leoSsoPlane = ['LEO-SSO'];
  // 获取所有MEO轨道面
  const meoPolarPlanes = Object.keys(ORBIT_PLANES).filter(id => id.startsWith('MEO-POLAR'));
  const meo60Planes = Object.keys(ORBIT_PLANES).filter(id => id.startsWith('MEO-') && !id.startsWith('MEO-POLAR'));
  // 获取所有GEO轨道面
  const geoPlanes = Object.keys(ORBIT_PLANES).filter(id => id === 'GEO');
  // 获取所有SGO轨道面
  const sgoWestPlanes = Object.keys(ORBIT_PLANES).filter(id => id === 'SGO-WEST');
  const sgoIndianPlanes = Object.keys(ORBIT_PLANES).filter(id => id === 'SGO-INDIAN');
  
  // 分配LEO卫星
  const leoSsoCount = Math.ceil(leoSatellites.length * 0.1); // 10%的LEO卫星分配到太阳同步轨道
  const leoSsoSatellites = leoSatellites.slice(0, leoSsoCount);
  const leoNormalSatellites = leoSatellites.slice(leoSsoCount);
  
  distributeSatellitesEvenly(leoSsoSatellites, leoSsoPlane, satellitesByOrbit);
  distributeSatellitesEvenly(leoNormalSatellites, leoPlanes, satellitesByOrbit);
  
  // 分配MEO卫星
  const meoPolarCount = Math.ceil(meoSatellites.length * 0.3); // 30%的MEO卫星分配到极轨道
  const meoPolarSatellites = meoSatellites.slice(0, meoPolarCount);
  const meo60Satellites = meoSatellites.slice(meoPolarCount);
  
  distributeSatellitesEvenly(meoPolarSatellites, meoPolarPlanes, satellitesByOrbit);
  distributeSatellitesEvenly(meo60Satellites, meo60Planes, satellitesByOrbit);
  
  // 分配GEO卫星
  distributeSatellitesEvenly(geoSatellites, geoPlanes, satellitesByOrbit);
  
  // 分配SGO卫星
  const sgoWestCount = Math.ceil(sgoSatellites.length * 0.5); // 50%的SGO卫星分配到西太组
  const sgoWestSatellites = sgoSatellites.slice(0, sgoWestCount);
  const sgoIndianSatellites = sgoSatellites.slice(sgoWestCount);
  
  distributeSatellitesEvenly(sgoWestSatellites, sgoWestPlanes, satellitesByOrbit);
  distributeSatellitesEvenly(sgoIndianSatellites, sgoIndianPlanes, satellitesByOrbit);
  
  return satellitesByOrbit;
};

/**
 * 在轨道面内均匀分布卫星
 */
const distributeSatellitesEvenly = (satellites, planeIds, satellitesByOrbit) => {
  if (!satellites.length || !planeIds.length) return;
  
  // 计算每个轨道面分配的卫星数量
  const satellitesPerPlane = Math.ceil(satellites.length / planeIds.length);
  
  // 分配卫星到轨道面
  planeIds.forEach((planeId, planeIndex) => {
    const startIndex = planeIndex * satellitesPerPlane;
    const endIndex = Math.min(startIndex + satellitesPerPlane, satellites.length);
    const planeSatellites = satellites.slice(startIndex, endIndex);
    
    // 将卫星添加到轨道面
    planeSatellites.forEach((sat, satIndex) => {
      const satWithIndex = { ...sat, planeIndex: satIndex, totalInPlane: planeSatellites.length };
      satellitesByOrbit[planeId].push(satWithIndex);
    });
  });
};

// 创建椭圆轨道（用于闪电轨道）
const createEllipticalOrbit = (periapsis, apoapsis, color, inclination) => {
  // 椭圆参数
  const semiMajorAxis = (periapsis + apoapsis) / 2;
  const eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis);
  
  const points = [];
  const segments = 128;
  
  for (let i = 0; i <= segments; i++) {
    const theta = (i / segments) * Math.PI * 2;
    
    // 计算基本位置
    const radius = semiMajorAxis * (1 - eccentricity * eccentricity) / (1 + eccentricity * Math.cos(theta));
    const x = radius * Math.cos(theta);
    const y = radius * Math.sin(theta) * Math.cos(inclination * Math.PI / 180);
    const z = radius * Math.sin(theta) * Math.sin(inclination * Math.PI / 180);
    points.push([x, y, z]);
  }
  
  return points;
};
/**
 * 卫星地球三维视图组 
 * 定义主组件,接受选中的卫星和轨道可见性为props
 */
const SatelliteEarthThree = ({ selectedSatellite, orbitVisibility }) => {
  // 引用
  const containerRef = useRef(null);
  const sceneRef = useRef(null);
  const cameraRef = useRef(null);
  const rendererRef = useRef(null);
  const controlsRef = useRef(null);
  const animationFrameRef = useRef(null);
  const earthRef = useRef(null);
  const clouds = useRef(null);
  const atmosphere = useRef(null);
  const orbitLinesRef = useRef({});
  const satelliteMeshesRef = useRef({});
  const orbitPointsCache = useRef({});
  const positionAnimationRef = useRef(null);
  const isMountedRef = useRef(false);

  // 状态
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [initialized, setInitialized] = useState(false);
  
  // 固定配置
  const autoRotate = false; // 自动旋转默认关闭
  const cameraDistance = 5; // 默认相机距离
  
  // WebSocket数据
  const { satellites, lastForceUpdate } = useWebSocket();
  
  // 创建卫星对象
  const createSatelliteMesh = useCallback((size, color, position) => {
    if (!sceneRef.current) {
      console.error('创建卫星对象失败: sceneRef.current 不存在');
      return null;
    }
    
    try {
      // 增加卫星大小以提高可见性
      const adjustedSize = size * 1.0; // 将卫星大小缩小为原来的1/3
      
      // 使用球体几何体
      const geometry = new THREE.SphereGeometry(adjustedSize, 8, 8);
      
      // 使用基本材质
      const material = new THREE.MeshBasicMaterial({ 
        color: new THREE.Color(color),
        transparent: false,
        opacity: 1.0
      });
      
      const satellite = new THREE.Mesh(geometry, material);
      if (position) satellite.position.copy(position);
      
      // 直接添加到场景中
      sceneRef.current.add(satellite);
      
      return satellite;
    } catch (error) {
      console.error('创建卫星对象失败:', error);
      return null;
    }
  }, []);
  
  useEffect(() => {
    console.log('组件挂载');
    isMountedRef.current = true;
    
    return () => {
      console.log('组件卸载');
      isMountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    if (!containerRef.current) return;
    
    // 初始化3D场景
    if (initialized) {
      console.log('已经初始化3D场景，跳过');
      return;
    }
    
    try {
      console.log('初始化3D场景');
      
      // 创建场景
      const scene = new THREE.Scene();
      sceneRef.current = scene;
      
      // 创建一个纹理加载器并设置跨域
      const textureLoader = new THREE.TextureLoader();
      textureLoader.crossOrigin = 'anonymous';
      
      // 使用纯黑色背景代替星空背景
      scene.background = new THREE.Color(0x000000);
      
      // 加载地球日间纹理
      const createFallbackTexture = (color) => {
        const canvas = document.createElement('canvas');
        canvas.width = 256;
        canvas.height = 256;
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = color;
        ctx.fillRect(0, 0, 256, 256);
        const texture = new THREE.CanvasTexture(canvas);
        return texture;
      };
      
      const fallbackEarthTexture = createFallbackTexture('#1a4d7c');
      const fallbackNormalTexture = createFallbackTexture('#808080');
      const fallbackSpecularTexture = createFallbackTexture('#111111');
      const fallbackCloudsTexture = createFallbackTexture('rgba(255, 255, 255, 0.5)');
      
      let earthDayTexture;
      try {
        earthDayTexture = textureLoader.load('/textures/earth-day-map.jpg', 
          () => console.log('地球日间纹理加载成功'),
          undefined,
          () => {
            console.error('地球日间纹理加载失败，使用备用方案');
            earthDayTexture = fallbackEarthTexture;
          }
        );
      } catch (error) {
        console.error('地球日间纹理加载异常:', error);
        earthDayTexture = fallbackEarthTexture;
      }
      
      // 加载地球法线贴图
      let normalMapTexture;
      try {
        normalMapTexture = textureLoader.load('/textures/earth-normal-map.jpg',
          () => console.log('地球法线贴图加载成功'),
          undefined,
          () => {
            console.error('地球法线贴图加载失败，使用备用方案');
            normalMapTexture = fallbackNormalTexture;
          }
        );
      } catch (error) {
        console.error('地球法线贴图加载异常:', error);
        normalMapTexture = fallbackNormalTexture;
      }
      
      // 加载地球高光贴图
      let specularMapTexture;
      try {
        specularMapTexture = textureLoader.load('/textures/earth-specular-map.jpg',
          () => console.log('地球高光贴图加载成功'),
          undefined,
          () => {
            console.error('地球高光贴图加载失败，使用备用方案');
            specularMapTexture = fallbackSpecularTexture;
          }
        );
      } catch (error) {
        console.error('地球高光贴图加载异常:', error);
        specularMapTexture = fallbackSpecularTexture;
      }
      
      // 加载云层纹理
      let cloudsTexture;
      try {
        cloudsTexture = textureLoader.load('/textures/earth-clouds.png',
          () => console.log('云层纹理加载成功'),
          undefined,
          () => {
            console.error('云层纹理加载失败，使用备用方案');
            cloudsTexture = fallbackCloudsTexture;
          }
        );
      } catch (error) {
        console.error('云层纹理加载异常:', error);
        cloudsTexture = fallbackCloudsTexture;
      }
      
      // 创建地球
      const earthGeometry = new THREE.SphereGeometry(1, 64, 64);
      
      // 创建地球材质
      const earthMaterial = new THREE.MeshPhongMaterial({
        map: earthDayTexture,
        normalMap: normalMapTexture,
        normalScale: new THREE.Vector2(0.85, 0.85),
        specularMap: specularMapTexture,
        specular: new THREE.Color(0x333333),
        shininess: 25,
        bumpMap: normalMapTexture,
        bumpScale: 0.05,
      });
      
      const earth = new THREE.Mesh(earthGeometry, earthMaterial);
      scene.add(earth);
      earthRef.current = earth;
      
      // 创建云层
      const cloudsGeometry = new THREE.SphereGeometry(1.01, 64, 64); // 略大于地球
      const cloudsMaterial = new THREE.MeshPhongMaterial({
        map: cloudsTexture,
        transparent: true,
        opacity: 0.8,
        blending: THREE.CustomBlending,
        blendSrc: THREE.SrcAlphaFactor,
        blendDst: THREE.OneMinusSrcAlphaFactor
      });
      
      const cloudsMesh = new THREE.Mesh(cloudsGeometry, cloudsMaterial);
      scene.add(cloudsMesh);
      clouds.current = cloudsMesh;
      
      // 创建大气层发光效果
      const atmosphereGeometry = new THREE.SphereGeometry(1.02, 64, 64); // 略大于云层
      const atmosphereMaterial = new THREE.MeshPhongMaterial({
        color: new THREE.Color(0x4ca6ff),
        transparent: true,
        opacity: 0.2,
        side: THREE.BackSide
      });
      
      const atmosphereMesh = new THREE.Mesh(atmosphereGeometry, atmosphereMaterial);
      scene.add(atmosphereMesh);
      atmosphere.current = atmosphereMesh;
      
      // 创建相机
      const camera = new THREE.PerspectiveCamera(
        75,
        containerRef.current.clientWidth / containerRef.current.clientHeight,
        0.1,
        1000
      );
      camera.position.set(0, 0, cameraDistance);
      camera.lookAt(0, 0, 0);
      cameraRef.current = camera;
      
      // 创建渲染器
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize(containerRef.current.clientWidth, containerRef.current.clientHeight);
      renderer.setPixelRatio(window.devicePixelRatio);
      
      // 清空容器并添加渲染器
      while (containerRef.current.firstChild) {
        containerRef.current.removeChild(containerRef.current.firstChild);
      }
      containerRef.current.appendChild(renderer.domElement);
      rendererRef.current = renderer;
      
      // 添加控制器
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.dampingFactor = 0.05;
      controls.autoRotate = autoRotate;
      controls.autoRotateSpeed = 0.5;
      controlsRef.current = controls;
      
      // 中国大致在地理坐标：经度104°E，纬度35°N
      const chinaLat = 35 * (Math.PI / 180); // 转为弧度
      const chinaLng = 104 * (Math.PI / 180); // 转为弧度

      // 计算中国在球面上的位置
      const chinaX = Math.cos(chinaLat) * Math.cos(chinaLng);
      const chinaY = Math.sin(chinaLat);
      const chinaZ = Math.cos(chinaLat) * Math.sin(chinaLng);
      
      // 添加环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.15);
      scene.add(ambientLight);
      
      // 添加主太阳光光源 - 模拟太阳光照
      // 将太阳光位置设置在中国一侧，但更远，以自然照亮中国区域
      const sunLight = new THREE.DirectionalLight(0xffffff, 1.2);
      sunLight.position.set(chinaX * 5, chinaY * 5 + 2, chinaZ * 5); // 将光源放在中国上方偏远处，模拟太阳
      sunLight.castShadow = true; // 启用阴影
      scene.add(sunLight);
      
      // 添加辅助光源 - 模拟从其他方向反射来的光
      const fillLight = new THREE.DirectionalLight(0x3366ff, 0.3); // 蓝色调的填充光
      fillLight.position.set(-chinaX * 5, -chinaY * 5, -chinaZ * 5); // 从相反方向照射
      scene.add(fillLight);

      // 添加地球边缘光
      const rimLight = new THREE.DirectionalLight(0x4ca6ff, 0.5);
      rimLight.position.set(-chinaX * 3, chinaY * 3, -chinaZ * 3);
      scene.add(rimLight);

      // 添加点光源
      const pointLight = new THREE.PointLight(0xffffff, 0.5);
      pointLight.position.set(chinaX * 3, chinaY * 3, chinaZ * 3);
      scene.add(pointLight);

      // 创建轨道和卫星
      const createOrbitLine = (points, color) => {
        const orbitGeometry = new THREE.BufferGeometry();
        const vertices = [];
        
        // 将点数组转换为顶点数组
        points.forEach(point => {
          vertices.push(point[0], point[1], point[2]);
        });
        
        orbitGeometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
        const orbitMaterial = new THREE.LineBasicMaterial({ color: new THREE.Color(color) });
        const orbitLine = new THREE.Line(orbitGeometry, orbitMaterial);
        scene.add(orbitLine);
        
        return orbitLine;
      };
      
      // 生成轨道线和轨道点
      const orbitLines = {};
      
      Object.entries(ORBIT_PLANES).forEach(([planeId, plane]) => {
        const orbitPoints = generateOrbitPoints(plane);
        orbitPointsCache.current[planeId] = orbitPoints;
        
        const orbitLine = createOrbitLine(orbitPoints, plane.color);
        orbitLines[planeId] = orbitLine;
        orbitLine.visible = orbitVisibility;
      });
      
      orbitLinesRef.current = orbitLines;
      
      // 设置地球初始旋转，使中国区域朝向摄像机
      earth.rotation.y = -chinaLng;
      
      setLoading(false);
      setInitialized(true);
      
      // 动画循环
      const animate = () => {
        if (!sceneRef.current || !cameraRef.current || !rendererRef.current) {
          console.error('动画循环需要场景、相机和渲染器');
          return;
        }
        
        animationFrameRef.current = requestAnimationFrame(animate);
        
        // 云层自转 - 减慢云层自转速度
        if (clouds.current) {
          clouds.current.rotation.y += 0.0003;
        }
        
        // 大气层发光效果 - 模拟日夜变化
        if (atmosphere.current) {
          const time = Date.now() * 0.0005;
          atmosphere.current.material.opacity = 0.15 + Math.sin(time) * 0.05;
        }
        
        // 更新控制器
        if (controlsRef.current) {
          controlsRef.current.update();
        }
        
        // 渲染场景
        try {
          rendererRef.current.render(sceneRef.current, cameraRef.current);
        } catch (error) {
          console.error('渲染场景失败:', error);
        }
      };
      
      animate();
      
      // 窗口大小调整
      const handleResize = () => {
        if (!containerRef.current || !cameraRef.current || !rendererRef.current) return;
        
        const width = containerRef.current.clientWidth;
        const height = containerRef.current.clientHeight;
        
        cameraRef.current.aspect = width / height;
        cameraRef.current.updateProjectionMatrix();
        rendererRef.current.setSize(width, height);
      };
      
      window.addEventListener('resize', handleResize);
      
      // 清理函数
      return () => {
        window.removeEventListener('resize', handleResize);
        if (animationFrameRef.current) {
          cancelAnimationFrame(animationFrameRef.current);
          animationFrameRef.current = null;
        }
        
        const container = containerRef.current;
        if (container && rendererRef.current && rendererRef.current.domElement) {
          try {
            container.removeChild(rendererRef.current.domElement);
          } catch (e) {
            console.error('清理DOM异常:', e);
          }
        }
        
        // 清理场景中的对象
        if (sceneRef.current) {
          while(sceneRef.current.children.length > 0){ 
            const object = sceneRef.current.children[0];
            sceneRef.current.remove(object);
            if (object.geometry) object.geometry.dispose();
            if (object.material) {
              if (Array.isArray(object.material)) {
                object.material.forEach(material => material.dispose());
              } else {
                object.material.dispose();
              }
            }
          }
        }
        
        if (rendererRef.current) {
          rendererRef.current.dispose();
          rendererRef.current = null;
        }
        
        // 清理引用
        sceneRef.current = null;
        cameraRef.current = null;
        controlsRef.current = null;
        earthRef.current = null;
        clouds.current = null;
        atmosphere.current = null;
        
        // 清理缓存
        orbitLinesRef.current = {};
        satelliteMeshesRef.current = {};
        orbitPointsCache.current = {};
      };
    } catch (error) {
      console.error('3D场景初始化失败:', error);
      setError(`3D场景初始化失败: ${error.message}`);
      setLoading(false);
    }
  }, []);
  
  useEffect(() => {
    if (orbitLinesRef.current) {
      Object.values(orbitLinesRef.current).forEach(line => {
        line.visible = orbitVisibility;
      });
    }
  }, [orbitVisibility]);
  
  useEffect(() => {
    if (controlsRef.current) {
      controlsRef.current.autoRotate = autoRotate;
    }
  }, [autoRotate]);
  
  // 单独处理卫星数据更新
  useEffect(() => {
    if (!initialized || !sceneRef.current) {
      console.log('场景未初始化，跳过卫星数据更新');
      return;
    }
    
    if (!satellites || satellites.length === 0) {
      console.log('没有卫星数据，跳过更新');
      return;
    }
    
    console.log(`接收到${satellites.length}颗卫星数据，准备更新, lastForceUpdate: ${lastForceUpdate}`);
    
    // 立即处理卫星数据更新
    try {
      console.log('处理卫星数据更新:', satellites.length);
      
      // 按轨道面分配卫星
      const satellitesByOrbit = assignSatellitesToOrbitPlanes(satellites);
      
      // 存储当前卫星状态
      const currentSatelliteStates = {};
      
      // 完全重新创建所有卫星模型
      // 首先移除所有现有的卫星模型
      Object.keys(satelliteMeshesRef.current).forEach(satId => {
        const mesh = satelliteMeshesRef.current[satId];
        if (mesh && sceneRef.current) {
          console.log(`移除卫星: ${satId}`);
          sceneRef.current.remove(mesh);
          if (mesh.geometry) mesh.geometry.dispose();
          if (mesh.material) {
            if (Array.isArray(mesh.material)) {
              mesh.material.forEach(material => material.dispose());
            } else {
              mesh.material.dispose();
            }
          }
        }
      });
      
      // 清空卫星模型引用
      satelliteMeshesRef.current = {};
      
      // 重新创建所有卫星模型
      updateSatelliteMeshes(satellitesByOrbit);
      
      // 强制重新渲染一次
      if (rendererRef.current && sceneRef.current && cameraRef.current) {
        console.log('强制重新渲染场景');
        rendererRef.current.render(sceneRef.current, cameraRef.current);
      }
    } catch (error) {
      console.error('更新卫星数据失败:', error);
    }
  }, [satellites, initialized, lastForceUpdate]);
  
  // 单独处理卫星模型更新
  const updateSatelliteMeshes = (satellitesByOrbit) => {
    // 创建或更新所有卫星的模型
    Object.entries(satellitesByOrbit).forEach(([planeId, sats]) => {
      const orbitPoints = orbitPointsCache.current[planeId];
      if (!orbitPoints) {
        console.warn(`轨道面 ${planeId} 的轨道点不存在`);
        return;
      }
      
      console.log(`更新轨道面 ${planeId} 的 ${sats.length} 个卫星模型`);
      
      sats.forEach((sat, index) => {
        const satId = sat.id;
        
        // 如果卫星模型不存在，创建一个新的
        if (!satelliteMeshesRef.current[satId]) {
          const plane = ORBIT_PLANES[planeId];
          if (!plane) {
            console.warn(`轨道面 ${planeId} 不存在于配置中`);
            return;
          }
          
          // 根据轨道类型调整卫星大小
          let satSize;
          if (plane.type === 'geo') {
            satSize = 0.08; // 增大GEO卫星尺寸
          } else if (plane.type === 'meo') {
            satSize = 0.06; // 增大MEO卫星尺寸
          } else if (plane.type === 'sgo') {
            satSize = 0.08; // 增大SGO卫星尺寸
          } else {
            satSize = 0.04; // 增大LEO卫星尺寸
          }
          
          const satColor = sat.status ? STATUS_COLORS[sat.status] : plane.color;
          
          // 创建卫星模型
          const mesh = createSatelliteMesh(satSize, satColor);
          if (mesh) {
            satelliteMeshesRef.current[satId] = mesh;
            
            // 存储轨道面和卫星ID以及轨道面内的索引和总数
            satelliteMeshesRef.current[satId].userData = {
              orbitPlane: planeId,
              satelliteId: satId,
              initialPhase: 0, // 不再使用随机初始相位，而是完全依赖planeIndex和totalInPlane
              planeIndex: sat.planeIndex || 0,
              totalInPlane: sat.totalInPlane || 1
            };
            
            console.log(`创建卫星模型: ID=${satId}, 轨道=${planeId}, 索引=${sat.planeIndex}/${sat.totalInPlane}`);
            
            // 立即计算并设置初始位置
            const timestamp = Date.now();
            const position = calculateSatellitePosition(
              orbitPoints, 
              timestamp, 
              satId, 
              1, 
              satelliteMeshesRef.current[satId].userData.initialPhase,
              satelliteMeshesRef.current[satId].userData.planeIndex,
              satelliteMeshesRef.current[satId].userData.totalInPlane
            );
            
            const lat = position.lat * Math.PI / 180;
            const lng = position.lng * Math.PI / 180;
            const r = 1 + position.alt;
            const x = r * Math.cos(lat) * Math.cos(lng);
            const y = r * Math.sin(lat);
            const z = r * Math.cos(lat) * Math.sin(lng);
            
            mesh.position.set(x, y, z);
            mesh.visible = true;
          }
        }
      });
    });
    
    // 移除不存在的卫星模型
    const existingSatIds = new Set(satellites.map(sat => sat.id));
    Object.keys(satelliteMeshesRef.current).forEach(satId => {
      if (!existingSatIds.has(satId)) {
        const mesh = satelliteMeshesRef.current[satId];
        if (mesh && sceneRef.current) {
          console.log(`移除不存在的卫星: ${satId}`);
          sceneRef.current.remove(mesh);
          mesh.geometry.dispose();
          mesh.material.dispose();
          delete satelliteMeshesRef.current[satId];
        }
      }
    });
  };
  
  // 单独处理卫星位置更新
  useEffect(() => {
    if (!initialized) return;
    
    console.log('开始更新卫星位置');
    
    // 单独处理卫星位置更新
    const updateSatellitePositions = () => {
      if (!isMountedRef.current || !sceneRef.current) return;
      
      const timestamp = Date.now();
      const satelliteCount = Object.keys(satelliteMeshesRef.current).length;
      
      if (satelliteCount === 0) {
        // 没有卫星，继续等待
        console.log('u6ca1u6709u536bu661fu53efu66f4u65b0uff0cu7ee7u7eedu7b49u5f85');
        positionAnimationRef.current = requestAnimationFrame(updateSatellitePositions);
        return;
      }
      
      console.log(`u66f4u65b0${satelliteCount}u4e2au536bu661fu4f4du7f6e`);
      
      // u66f4u65b0u6240u6709u536bu661fu7684u4f4du7f6e
      Object.entries(satelliteMeshesRef.current).forEach(([satId, mesh]) => {
        if (!mesh || !mesh.userData) return;
        
        const { orbitPlane, initialPhase, planeIndex, totalInPlane } = mesh.userData;
        const orbitPoints = orbitPointsCache.current[orbitPlane];
        
        if (!orbitPoints) {
          console.warn(`u8f68u9053u70b9u4e0du5b58u5728: ${orbitPlane}`);
          return;
        }
        
        // u8ba1u7b97u536bu661fu4f4du7f6e
        const position = calculateSatellitePosition(orbitPoints, timestamp, satId, 1, initialPhase, planeIndex, totalInPlane);
        const lat = position.lat * Math.PI / 180;
        const lng = position.lng * Math.PI / 180;
        const r = 1 + position.alt;
        const x = r * Math.cos(lat) * Math.cos(lng);
        const y = r * Math.sin(lat);
        const z = r * Math.cos(lat) * Math.sin(lng);
        
        // u66f4u65b0u4f4du7f6e
        mesh.position.set(x, y, z);
        
        // u786eu4fddu536bu661fu53efu89c1
        mesh.visible = true;
        
        // u9009u4e2du7684u536bu661fu653eu5927u663eu793a
        if (selectedSatellite && selectedSatellite.id === satId) {
          mesh.scale.set(1.5, 1.5, 1.5);
        } else {
          mesh.scale.set(1, 1, 1);
        }
      });
      
      // u7ee7u7eedu66f4u65b0
      positionAnimationRef.current = requestAnimationFrame(updateSatellitePositions);
    };
    
    // u5f00u59cbu66f4u65b0
    positionAnimationRef.current = requestAnimationFrame(updateSatellitePositions);
    
    // u6e05u7406u51fdu6570
    return () => {
      console.log('u6e05u7406u536bu661fu4f4du7f6eu66f4u65b0');
      if (positionAnimationRef.current) {
        cancelAnimationFrame(positionAnimationRef.current);
        positionAnimationRef.current = null;
      }
    };
  }, [initialized, selectedSatellite]);

  // 渲染UI
  return (
    <Box sx={{ position: 'relative', width: '100%', height: '100%', overflow: 'hidden', border: '1px solid rgba(88, 175, 223, 0.3)', zIndex: 10 }}>
      {/* 3D容器 */}
      <Box 
        ref={containerRef} 
        sx={{ 
          width: '100%', 
          height: '100%', 
          backgroundColor: '#000', 
          position: 'relative',
          border: '1px solid rgba(88, 175, 223, 0.3)',
          zIndex: 11
        }}
        data-testid="earth-container"
      />
      
      {/* 轨道层标注 - 右侧 */}
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          right: 20,
          transform: 'translateY(-50%)',
          display: 'flex',
          flexDirection: 'column',
          gap: 2,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          padding: 1.5,
          borderRadius: 1,
          zIndex: 12,
          color: 'white',
          fontWeight: 'bold',
          boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)'
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 16,
              height: 16,
              backgroundColor: '#64b5f6', // 低轨颜色
              borderRadius: '2px'
            }}
          />
          <Typography variant="body2" sx={{ color: 'white' }}>
            低轨突击层
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 16,
              height: 16,
              backgroundColor: '#ba68c8', // 中轨颜色
              borderRadius: '2px'
            }}
          />
          <Typography variant="body2" sx={{ color: 'white' }}>
            中轨警戒层
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Box
            sx={{
              width: 16,
              height: 16,
              backgroundColor: '#ffd54f', // 静轨颜色
              borderRadius: '2px'
            }}
          />
          <Typography variant="body2" sx={{ color: 'white' }}>
            静轨威慑层
          </Typography>
        </Box>
      </Box>
      
      {/* 加载指示器 */}
      {loading && (
        <Box sx={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
          <CircularProgress />
        </Box>
      )}
      
      {/* 错误提示 */}
      {error && (
        <Box sx={{ position: 'absolute', top: 16, left: 16, right: 16 }}>
          <Alert severity="error">{error}</Alert>
        </Box>
      )}
    </Box>
  );
};

export default SatelliteEarthThree;
